package com.mall.web.control.weishang;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.biz.ErWeiMaBizImpl;
import com.mall.biz.trade.TradeBizImpl;
import com.mall.biz.weishang.TransferAuditBizImpl;
import com.mall.client.item.MallItemService;
import com.mall.client.mall.MallActivityService;
import com.mall.client.mall.MallService;
import com.mall.client.mallCategory.MallCategoryService;
import com.mall.client.trade.TradeService;
import com.mall.client.user.TransferAuditService;
import com.mall.client.user.UserExtendedService;
import com.mall.client.user.UserLevelService;
import com.mall.client.user.UserService;
import com.mall.common.util.DateUtil;
import com.mall.common.util.PageUtil;
import com.mall.constant.UserConstant;
import com.mall.enums.MallActivityEnum;
import com.mall.pojo.Mall;
import com.mall.pojo.MallActivity;
import com.mall.pojo.MallCategory;
import com.mall.pojo.MallCategoryExample;
import com.mall.pojo.MallCategoryExample.Criteria;
import com.mall.pojo.Trade;
import com.mall.pojo.TradeExample;
import com.mall.pojo.TransferAudit;
import com.mall.pojo.User;
import com.mall.pojo.UserExtended;
import com.mall.pojo.UserLevel;
import com.mall.query.MallActivityQuery;
import com.mall.query.Page;
import com.mall.query.TradeRecordQuery;
import com.mall.query.TransferAuditQuery;
import com.mall.vo.common.CategoryVO;
import com.mall.vo.trade.TradeVO;
import com.mall.vo.weishang.TransferAuditVO;
import com.mall.web.annotation.AdminSecurity;
import com.mall.web.util.HttpUtil;
import com.mall.web.util.MoneyUtil;
import com.mall.web.util.WebUtil;
import com.mall.web.vo.ResponseEntity;

@Controller
@RequestMapping("/weishang/supplier/")
public class WeishangSupplierController {
	private final Logger log = LoggerFactory.getLogger(WeishangSupplierController.class);
	
	@Autowired
	private MallCategoryService mallCategoryService;
	@Autowired
	private MallService mallService;
	@Autowired
	private TradeBizImpl tradeBizImpl;
	@Autowired
	private TradeService tradeService;
	@Autowired
	private UserLevelService userLevelService;
	@Autowired
	private MallActivityService mallActivityService;
	@Autowired
	private MallItemService mallItemService;
	@Autowired
	private ErWeiMaBizImpl erWeiMaBiz;
	@Autowired
	private TransferAuditService transferAuditService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserExtendedService userExtendedService;
	@Autowired
	private TransferAuditBizImpl transferAuditBizImpl;

	@RequestMapping("supplierIndex")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String weishangIndex(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		User user = WebUtil.getCurrentUser(request);
		Mall mall = this.mallService.getMallByOnlyKey(onlyKey);
		if(mall == null){
			mall = new Mall();
			mall.setSellerId(user.getId());
			mall.setCommOnlyKey(onlyKey);
			mall.setCreateUserId(user.getId());
			mall.setMallName(user.getPhone());
			mall.setMallType(0);
			mall.setType(0);
			mall.setSsig(0l);
			mall.setMainPic("供应商主图");
			mall.setGmtCreate(new Date());
			mall.setGmtModify(new Date());
			int result = this.mallService.insertMall(mall);
			if (result <=0) {
				log.error("mall insert is error");
			}
		}
		TradeRecordQuery tradeRecordQuery = new TradeRecordQuery();
		tradeRecordQuery.setMallId(mall.getId());
		tradeRecordQuery.setType(89);//余额支付
		tradeRecordQuery.setOnlyKey(onlyKey);
		String startTime = DateUtil.dateToString(new Date(), DateUtil.ymd) + " 00:00:00";
		String endTime = DateUtil.dateToString(new Date(), DateUtil.ymd) + " 23:59:59";
		tradeRecordQuery.setStartTime(DateUtil.stringToDate(startTime, DateUtil.ymdhms));
		tradeRecordQuery.setEndTime(DateUtil.stringToDate(endTime, DateUtil.ymdhms));
		TradeExample example = this.tradeBizImpl.getTradeExampleByQuery(tradeRecordQuery);
		// 今天创建的订单
		int tradeCount = this.tradeService.getTradeCount(example);
		// 今天创建订单的用户总数
		Integer userNums = this.tradeService.getUserNumByExample(example);
		// 今天付款订单总价
		tradeRecordQuery.setStatus(4);
		example = this.tradeBizImpl.getTradeExampleByQuery(tradeRecordQuery);
		Long sumPrice = this.tradeService.getSumPriceByExample(example);
		this.tradeService.getTradeMessListByExample(example);
		modelMap.put("mall", mall);
		modelMap.put("tradeCount", tradeCount);
		modelMap.put("userNums", userNums);
		modelMap.put("sumPrice", sumPrice);
		modelMap.put("user", user);
		return "weishang/supplier/supplierIndex";
	}

	/**
	 * 类目列表
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("categoryManage")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String categoryManager(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		MallCategoryExample mallCategoryExample = new MallCategoryExample();
		Criteria criteria = mallCategoryExample.createCriteria();
		criteria.andCommOnlyKeyEqualTo(onlyKey);
		criteria.andStatusEqualTo(0);
		List<MallCategory> mallCategoryList = this.mallCategoryService.getMallCategoryList(mallCategoryExample);
		criteria.andParentIdEqualTo(0);
		List<MallCategory> firstCategoryList = this.mallCategoryService.getMallCategoryList(mallCategoryExample);

		List<CategoryVO> categoryVOList = new ArrayList<CategoryVO>();
		if (firstCategoryList != null && firstCategoryList.size() > 0) {
			for (MallCategory firstCategory : firstCategoryList) {
				CategoryVO categoryVO = new CategoryVO();
				List<MallCategory> categoryList = new ArrayList<MallCategory>();
				for (MallCategory secCategory : mallCategoryList) {
					if (secCategory.getParentId().intValue() == firstCategory.getId().intValue()) {
						categoryList.add(secCategory);
					}
				}
				categoryVO.setFirstCategory(firstCategory);
				categoryVO.setSecCategoryList(categoryList);
				categoryVOList.add(categoryVO);
			}
		}
		modelMap.put("categoryVOList", categoryVOList);
		return "weishang/supplier/categoryManage";
	}

	/**
	 * 增加类目
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("addCategory")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public ResponseEntity<String> addCategory(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		User user = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		ResponseEntity<String> responseEntity = new ResponseEntity<>();
		Integer categoryId = HttpUtil.getIntegerValueFromRequest(request, "categoryId");
		String categoryName = HttpUtil.getStringValueFromRequest(request, "categoryName");
		MallCategory mallCategory = new MallCategory();
		mallCategory.setParentId(categoryId);
		mallCategory.setName(categoryName);
		mallCategory.setCreateUserId(user.getId());
		mallCategory.setStatus(0);
		mallCategory.setType(0);
		mallCategory.setCommOnlyKey(onlyKey);
		int isInsert = this.mallCategoryService.addMallCategoryByMallCategory(mallCategory);
		if (isInsert <= 0) {
			responseEntity.setCode("-200");
			responseEntity.setData(null);
			responseEntity.setMessage("增加失败");
			return responseEntity;
		}
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("增加成功");
		return responseEntity;
	}

	/**
	 * 删除类目
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("deleteCategory")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@Transactional
	public ResponseEntity<String> deleteCategory(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		ResponseEntity<String> responseEntity = new ResponseEntity<>();
		Integer categoryId = HttpUtil.getIntegerValueFromRequest(request, "categoryId");
		MallCategory mallCategory = this.mallCategoryService.getMallCategoryById(categoryId);
		if (mallCategory == null) {
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("类目不存在");
			return responseEntity;
		}

		// 目录下的商品全部删除（修改状态为-8）
		// 类目状态修改为-1
		List<Integer> ids = new ArrayList<Integer>();
		if (mallCategory.getParentId() == 0) {
			ids.add(mallCategory.getId());
			List<MallCategory> mallCategoryList = this.mallCategoryService
					.getSecMallCategoryListByParentMallCategoryId(mallCategory.getId());
			if (mallCategoryList != null && mallCategoryList.size() > 0) {
				for (MallCategory secCategory : mallCategoryList) {
					ids.add(secCategory.getId());
				}
			}
		} else {
			ids.add(mallCategory.getId());
		}
		this.mallItemService.updateMallItemByIds(ids);
		this.mallCategoryService.updateStatusByIds(ids);
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("删除成功");
		return responseEntity;
	}

	/**
	 * 修改类目
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("modifyCategory")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public ResponseEntity<String> modifyCategory(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		ResponseEntity<String> responseEntity = new ResponseEntity<>();
		Integer categoryId = HttpUtil.getIntegerValueFromRequest(request, "categoryId");
		MallCategory mallCategory = this.mallCategoryService.getMallCategoryById(categoryId);
		if (mallCategory == null) {
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("类目不存在");
			return responseEntity;
		}
		String categoryName = HttpUtil.getStringValueFromRequest(request, "categoryName");
		mallCategory.setName(categoryName);
		mallCategory.setGmtModify(new Date());
		int isModify = this.mallCategoryService.modifyMallCategoryByMallCategory(mallCategory);
		if (isModify <= 0) {
			responseEntity.setCode("-200");
			responseEntity.setData(null);
			responseEntity.setMessage("修改失败");
			return responseEntity;
		}
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("修改成功");
		return responseEntity;
	}

	// 编辑商品信息 价格设置
	@RequestMapping("priceSet")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String priceSet(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		return "weishang/supplier/priceSet";
	}

	// 编辑商品信息 不同级别分销商价格设置
	@RequestMapping("distributorSet")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String distributorSet(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		return "weishang/supplier/distributorSet";
	}

	/**
	 * 供应商增加分销商级别
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("distributorLevelSet")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String distributorLevelSet(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		List<UserLevel> userLevelList = this.userLevelService.getUserLevelListByKey(onlyKey);
		modelMap.put("userLevelList", userLevelList);
		return "weishang/supplier/distributorLevelSet";
	}

	/**
	 * 新增或修改level
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("saveDistributorLevel")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public ResponseEntity<String> saveDistributorLevel(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Integer level = HttpUtil.getIntegerValueFromRequest(request, "level");
		String levelName = HttpUtil.getStringValueFromRequest(request, "levelName");
		String lowPrice = HttpUtil.getStringValueFromRequest(request, "lowPrice");
		String highPrice = HttpUtil.getStringValueFromRequest(request, "highPrice");
		Long userLevelId = HttpUtil.getLongValueFromRequest(request, "userLevelId");

		if (userLevelId != null && userLevelId > 0) {
			return modifyLevel(onlyKey, highPrice, lowPrice,level, levelName);
		}

		return saveLevel(onlyKey, highPrice, level, levelName, lowPrice);
	}

	// 修改级别
	public ResponseEntity<String> modifyLevel(Integer onlyKey, String highPrice,String lowPrice, Integer level, String levelName) {
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		// 当前级别修改名称或最高消费金额
		UserLevel userLevel = this.userLevelService.getUserLevelByLevelAndKey(level, onlyKey);
		userLevel.setLevelName(levelName);
		userLevel.setHighPrice(MoneyUtil.getPriceByString(highPrice));
		userLevel.setLowPrice(MoneyUtil.getPriceByString(lowPrice));
		int isModifyLevel = this.userLevelService.modifyUserLevel(userLevel);
		if (isModifyLevel <= 0) {
			responseEntity.setCode("-200");
			responseEntity.setData(null);
			responseEntity.setMessage("修改失败");
			return responseEntity;
		}

		// 下一个级别修改相对应的最低消费金额
		UserLevel nexttUserLevel = this.userLevelService.getUserLevelByLevelAndKey(level + 1, onlyKey);
		if (nexttUserLevel != null) {
			nexttUserLevel.setLowPrice(MoneyUtil.getPriceByString(highPrice));
			int isModifyNextLevel = this.userLevelService.modifyUserLevel(nexttUserLevel);
			if (isModifyNextLevel <= 0) {
				responseEntity.setCode("-200");
				responseEntity.setData(null);
				responseEntity.setMessage("修改失败");
				return responseEntity;
			}
		}

		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("修改成功");
		return responseEntity;

	}

	/**
	 * 新增level
	 * 
	 * @param onlyKey
	 * @param highPrice
	 * @param level
	 * @param levelName
	 * @param lowPrice
	 * @return
	 */
	public ResponseEntity<String> saveLevel(Integer onlyKey, String highPrice, Integer level, String levelName,
			String lowPrice) {
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		UserLevel userLevel = new UserLevel();
		userLevel.setCommOnlyKey(onlyKey);
		userLevel.setHighPrice(MoneyUtil.getPriceByString(highPrice));
		userLevel.setLevel(level);
		userLevel.setLevelName(levelName);
		userLevel.setLowPrice(MoneyUtil.getPriceByString(lowPrice));
		userLevel.setStatus(0);
		userLevel.setType(0);

		int isInsertLevel = this.userLevelService.insertUserLevel(userLevel);
		if (isInsertLevel <= 0) {
			responseEntity.setCode("-200");
			responseEntity.setData(null);
			responseEntity.setMessage("添加失败");
			return responseEntity;
		}
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("添加成功");
		return responseEntity;

	}

	// 供应商发送消息
	@RequestMapping("sendMessage")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String sendMessage(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		List<UserLevel> userLevelList = this.userLevelService.getUserLevelListByKey(onlyKey);
		modelMap.put("userLevelList", userLevelList);
		return "weishang/supplier/sendMessage";
	}

	/**
	 * 发送公告的action
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("sendMessageAction")
	public String sendMessageAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		User user = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		MallActivity mallActivity = new MallActivity();
		String activityTitle = HttpUtil.getStringValueFromRequest(request, "activityTitle");
		String activityDesc = HttpUtil.getStringValueFromRequest(request, "activityDesc");
		String[] activityRull = request.getParameterValues("checkbox");
		mallActivity.setActivityDesc(activityDesc);
		mallActivity.setActivityTitle(activityTitle);
		//数组转字符串用逗号隔开
		mallActivity.setActivityRull(StringUtils.join(activityRull, ","));
		mallActivity.setCommOnlyKey(onlyKey);
		mallActivity.setUserId(user.getId());
		mallActivity.setType(MallActivityEnum.SELLERACTIVITY.getCode());
		mallActivity.setStatus(MallActivityEnum.USINGACTIVITY.getCode());
		int insertSuccess = this.mallActivityService.insertMallActivity(mallActivity);
		if (insertSuccess <= 0) {

			return "redirect:/weishang/supplier/error.htm";
		}
		return "redirect:/weishang/supplier/success.htm";
	}
	
	/**
	 * 供应商公告列表
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("messageList")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String messageList(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		messageListMap(request,response,modelMap);
		return "weishang/supplier/messageList";
	}
	
	/**
	 * 供应商公告详情
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("messageDetail")
	public String messageDetail(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		Long mallActivityId = HttpUtil.getLongValueFromRequest(request, "mallActivityId");
		MallActivity mallActivity =  this.mallActivityService.getMallActivityById(mallActivityId);
		modelMap.put("mallActivity", mallActivity);
		return "weishang/supplier/messageDetail";
	}
	public ModelMap messageListMap(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
		Page page = new Page();
		int pageNo = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageNo", 1);
		int pageSize = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageSize",PageUtil.PAGE_SIZE_MALL);
		page.setPageByPageNoAndPageSize(pageNo, pageSize);
		User user = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		MallActivityQuery mallActivityQuery = new  MallActivityQuery();
		mallActivityQuery.setCommkey(onlyKey);
		mallActivityQuery.setType(MallActivityEnum.SELLERACTIVITY.getCode());
		mallActivityQuery.setOrderBy("id desc");
		mallActivityQuery.setStatus(MallActivityEnum.USINGACTIVITY.getCode());
		
		
		List<MallActivity> mallActivityList = this.mallActivityService.getMallActivityList(mallActivityQuery, page);
		modelMap.put("mallActivityList", mallActivityList);
		modelMap.put("user", user);
		return modelMap;
		
	}
	/**
	 * 供应商删除公告
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("deleteMessage")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@ResponseBody
	public ResponseEntity<String> deleteMessage(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		User user = WebUtil.getCurrentUser(request);
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		Long mallActivityId = HttpUtil.getLongValueFromRequest(request, "mallActivityId");
		if (mallActivityId ==null ) {
			   responseEntity.initErrorResponseEntity(null, "delete error");
			   return responseEntity;
		   }
		MallActivity mallActivity =  this.mallActivityService.getMallActivityById(mallActivityId);
		mallActivity.setStatus(MallActivityEnum.UNUSINGACTIVIVTY.getCode());
		mallActivity.setUserId(user.getId());
	   Integer result =	this.mallActivityService.updateMallActivity(mallActivity, mallActivityId);
	   if (result !=null && result>0) {
		   responseEntity.initSuccResponseEntity(null, "delete success");
		   return responseEntity;
	   }
		return responseEntity;
	}
	

	/**
	 * 发送消息失败
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("error")
	public String error(HttpServletRequest request,HttpServletResponse response){
		return "weishang/supplier/error";
	}
	
	/**
	 * 发送消息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("success")
	public String orderSuccess(HttpServletRequest request,HttpServletResponse response){
		return "weishang/supplier/success";
	}
	/**
	 * 供应商的个人中心
	 * @param request
	 * @param response
	 * @return
	 */
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("supplierMine")
	public String supplierMine(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		User user = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Mall  mall = this.mallService.getMallByUserIdAndOnlyKey(user.getId(),onlyKey);
		if(mall == null){
			mall = new Mall();
			mall.setSellerId(user.getId());
			mall.setCommOnlyKey(onlyKey);
			mall.setCreateUserId(user.getId());
			mall.setMallName(user.getPhone());
			mall.setMallType(0);
			mall.setType(0);
			mall.setSsig(0l);
			mall.setMainPic("供应商主图");
			mall.setGmtCreate(new Date());
			mall.setGmtModify(new Date());
			int result = this.mallService.insertMall(mall);
			if (result <=0) {
				log.error("mall insert is error");
			}
		}
		Date date = new Date();
		Long dateNow = date.getTime();
		if (mall.getQrcodePic()==null) {
			boolean relust  = false;
			try {
			 relust  = erWeiMaBiz.createErWeiMaForMallQrcode(onlyKey, dateNow);
			} catch (Exception e) {
				e.printStackTrace();
			}
			String fileName = "weishang" + onlyKey + dateNow + ".png";
			if (relust) {
				mall.setQrcodePic("qrcode/"+fileName);
			   Integer relustInsert = 	this.mallService.modifyMallByPrimaryKey(mall);
			   mall = this.mallService.getMallById(mall.getId());
			   if (relustInsert == null || relustInsert<0) {
				   log.error("生成店铺二维码错误");
				return null;
			}
			}
		}
		modelMap.put("mall", mall);
		modelMap.put("user", user);
		return "weishang/supplier/supplierMine";
	}
	
	
	
	/**
	 * 供应商设置转账的银行卡
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("bankSet")
	public String bankSet(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		User user = WebUtil.getCurrentUser(request);
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(user.getId());
		modelMap.put("user", user);
		modelMap.put("userExtended", userExtended);
		return "weishang/supplier/bankSet";
	}
	
	
	/**
	 * 增加银行卡action
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("addBankInfoAction")
	@ResponseBody
	public ResponseEntity<String> addBankInfoAction(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		String accountName = HttpUtil.getStringValueFromRequest(request, "accountName");
		String accountBank = HttpUtil.getStringValueFromRequest(request, "accountBank");
		String accountCard = HttpUtil.getStringValueFromRequest(request, "accountCard").trim();
		if(accountName == null || accountBank == null || accountCard == null){
			responseEntity.initErrorResponseEntity(null, "信息不全");
			return responseEntity;
		}
		User user = WebUtil.getCurrentUser(request);
		
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(user.getId());
		userExtended.setAccountName(accountName);
		userExtended.setAccountBank(accountBank);
		userExtended.setAccountCard(accountCard);
		this.userExtendedService.updateExtendedByPrimaryKey(userExtended);
		responseEntity.initSuccResponseEntity(null, "增加银行卡成功");
		return responseEntity;
	}
	
	/**
	 * 删除银行卡action
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("deleteBankInfoAction")
	@ResponseBody
	public ResponseEntity<String> deleteBankInfoAction(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		User user = WebUtil.getCurrentUser(request);
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(user.getId());
		userExtended.setAccountName(null);
		userExtended.setAccountBank(null);
		userExtended.setAccountCard(null);
		this.userExtendedService.updateExtendedByPrimaryKey(userExtended);
		responseEntity.initSuccResponseEntity(null, "删除银行卡成功");
		return responseEntity;
	}
	
	
	
	/**
	 * 转账信息列表
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("transferRecordList")
	public String transferRecordList(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		transferRecordModelMap(request,response,modelMap);
		return "weishang/supplier/transferRecordList";
	}
	
	/**
	 * 转账信息列表
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("transferRecordMore")
	public String transferRecordListMore(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		transferRecordModelMap(request,response,modelMap);
		return "weishang/supplier/transferRecordMore";
	}
	
	private ModelMap transferRecordModelMap(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		Page page = new Page();
		int pageNo = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageNo", 1);
		int pageSize = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageSize",PageUtil.PAGE_SIZE_APP);
		page.setPageByPageNoAndPageSize(pageNo, pageSize);
		
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Integer status = HttpUtil.getIntegerValueFromRequest(request, "status");
		Integer type = HttpUtil.getIntegerValueFromRequest(request, "type");
		String phone = HttpUtil.getStringValueFromRequest(request, "phone");
		
		TransferAuditQuery transferAuditQuery = new TransferAuditQuery();
		transferAuditQuery.setPage(page);
		transferAuditQuery.setOnlyKey(onlyKey);
		transferAuditQuery.setPhone(phone);
		transferAuditQuery.setStatus(status);
		transferAuditQuery.setType(type);
		
		List<TransferAudit> transferAuditList = this.transferAuditBizImpl.getTransferAuditListByQuery(transferAuditQuery);
		
		List<TransferAuditVO> transferAuditVOList = new ArrayList<TransferAuditVO>();
		if(transferAuditList != null && transferAuditList.size() > 0){
			for(TransferAudit transferAudit : transferAuditList){
				TransferAuditVO transferAuditVO = new TransferAuditVO();
				User user = this.userService.getUserByUserId(transferAudit.getUserId());
				transferAuditVO.setTransferAudit(transferAudit);
				transferAuditVO.setUser(user);
				transferAuditVOList.add(transferAuditVO);
			}
		}
		modelMap.put("pageNo", pageNo);
		modelMap.put("pageSize", pageSize);
		modelMap.put("transferAuditVOList", transferAuditVOList);
		return modelMap;
	}
	
	
	
	/**
	 * 转账信息详情
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("transferRecordDetail")
	public String transferRecordDetail(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Long transferAuditId = HttpUtil.getLongValueFromRequest(request, "transferAuditId");
		TransferAudit transferAudit = this.transferAuditService.getTransferAuditById(transferAuditId);
		Mall mall = this.mallService.getMallByOnlyKey(onlyKey);
		if(transferAudit == null || mall == null){
			return null;
		}
		User user = this.userService.getUserByUserId(transferAudit.getUserId());
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(user.getId());
		//分销商想要成为的级别
		Integer wantLevel = Integer.parseInt((user.getLevel()+"").replace("-", "").trim());
		UserLevel userLevel = this.userLevelService.getUserLevelByLevelAndKey(wantLevel, onlyKey);
		
		modelMap.put("mallId", mall.getId());
		modelMap.put("user", user);
		modelMap.put("userLevel", userLevel);
		modelMap.put("userExtended", userExtended);
		modelMap.put("transferAudit", transferAudit);
		return "weishang/supplier/transferRecordDetail";
	}
	
	
	/**
	 * 供应商给分销商货款充钱
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("addBalanceAction")
	@ResponseBody
	public ResponseEntity<String> addBalanceAction(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		Long transferAuditId = HttpUtil.getLongValueFromRequest(request, "transferAuditId");
		TransferAudit transferAudit = this.transferAuditService.getTransferAuditById(transferAuditId);
		if(transferAudit == null){
			responseEntity.initErrorResponseEntity(null, "无法操作");
			return responseEntity;
		}
		//更新用户余额
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(transferAudit.getUserId());
		Double price = Double.parseDouble(request.getParameter("money"));
		Long addBalance = price.longValue();
		if(userExtended == null){
			userExtended = new UserExtended();
			userExtended.setBalance(addBalance);
		}else{
			userExtended.setBalance(addBalance+userExtended.getBalance());
		}
		this.userExtendedService.updateExtendedByPrimaryKey(userExtended);
		responseEntity.initSuccResponseEntity(null, "修改成功");
		return responseEntity;
	}
	
	
	/**
	 * 修改转账记录的状态
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("modifyTransferAuditRecordStatus")
	@ResponseBody
	public ResponseEntity<String> modifyTransferAuditRecordStatus(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		User currentUser = WebUtil.getCurrentUser(request);
		Integer status = HttpUtil.getIntegerValueFromRequest(request, "status");
		Long transferAuditId = HttpUtil.getLongValueFromRequest(request, "transferAuditId");
		TransferAudit transferAudit = this.transferAuditService.getTransferAuditById(transferAuditId);
		if(transferAudit == null || status == null){
			responseEntity.initErrorResponseEntity(null, "无法操作");
			return responseEntity;
		}
		//更新审核状态
		transferAudit.setOperationUserId(currentUser.getId());
		transferAudit.setStatus(status);
		this.transferAuditService.modifyTransferAudit(transferAudit);
		responseEntity.initSuccResponseEntity(null, "修改成功");
		return responseEntity;
	}
	
	
/*	*//**
	 * 审核完成进行充值
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 *//*
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("rechargeAction")
	@ResponseBody
	public ResponseEntity<String> rechargeAction(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		Long transferAuditId = HttpUtil.getLongValueFromRequest(request, "transferAuditId");
		Integer status = HttpUtil.getIntegerValueFromRequest(request, "status");
		TransferAudit transferAudit = this.transferAuditService.getTransferAuditById(transferAuditId);
		if(transferAudit == null || status == null){
			responseEntity.initErrorResponseEntity(null, "无法操作");
			return responseEntity;
		}
		Long bond = MoneyUtil.getPriceByString(HttpUtil.getStringValueFromRequest(request, "bond"));
		Long balance = MoneyUtil.getPriceByString(HttpUtil.getStringValueFromRequest(request, "balance"));
		User user = this.userService.getUserByUserId(transferAudit.getUserId());
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(transferAudit.getUserId());
		if(userExtended == null || user == null){
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("用户不存在");
		}
		userExtended.setBalance(userExtended.getBalance()+balance);
		userExtended.setBond(userExtended.getBond()+bond);
		this.userExtendedService.updateExtendedByPrimaryKey(userExtended);
		
		//如果用户还不是分销商，充值完成后完成升级
		Integer level = HttpUtil.getIntegerValueFromRequest(request, "level");
		if(level != null && level < 0){
			user.setLevel(Short.valueOf(level.toString().replace("-", "")));
			this.userService.modifytUserByPrimaryKey(user);
		}
		
		//更新审核状态
		User currentUser = WebUtil.getCurrentUser(request);
		transferAudit.setOperationUserId(currentUser.getId());
		transferAudit.setStatus(status);
		this.transferAuditService.modifyTransferAudit(transferAudit);
		responseEntity.initSuccResponseEntity(null, "修改成功");
		return responseEntity;
	}*/
	
	
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("rechargeList")
	public String rechargeList(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		rechargeListModelMap(request,response,modelMap);
		return "weishang/supplier/rechargeList";
	}
	
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@RequestMapping("rechargeListMore")
	public String rechargeListMore(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		rechargeListModelMap(request,response,modelMap);
		return "weishang/supplier/rechargeListMore";
	}
	
	private ModelMap rechargeListModelMap(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		Page page = new Page();
		int pageNo = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageNo", 1);
		int pageSize = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageSize",PageUtil.PAGE_SIZE_APP);
		page.setPageByPageNoAndPageSize(pageNo, pageSize);
		
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Integer buyItemType = HttpUtil.getIntegerValueFromRequest(request, "buyItemType");
		
		TradeRecordQuery tradeRecordQuery = new TradeRecordQuery();
		tradeRecordQuery.setOnlyKey(onlyKey);
		tradeRecordQuery.setType(90);
		tradeRecordQuery.setBuyItemType(buyItemType);
		tradeRecordQuery.setOrderby("gmt_modify desc");
		TradeExample example = this.tradeBizImpl.getTradeExampleByQuery(tradeRecordQuery);
		List<Trade> tradeList = this.tradeService.getTradeMessListByExample(example);
		
		List<TradeVO> tradeVOList = new ArrayList<TradeVO>();
		if(tradeList != null && tradeList.size() > 0){
			for(Trade trade : tradeList){
				TradeVO tradeVO = new TradeVO();
				User user = this.userService.getUserByUserId(trade.getBuyUserId());
				tradeVO.setTrade(trade);
				tradeVO.setUser(user);
				tradeVOList.add(tradeVO);
			}
		}
		modelMap.put("pageNo", pageNo);
		modelMap.put("pageSize", pageSize);
		modelMap.put("tradeVOList", tradeVOList);
		return modelMap;
	}
	
	
}
